package org.jflame.auth.session.springsession;

import org.jflame.auth.session.SessionInfo;
import org.jflame.auth.session.SessionRegistry;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.util.Assert;

public class SpringSessionBackedSessionRegistry<S extends Session> implements SessionRegistry {

    private final FindByIndexNameSessionRepository<S> sessionRepository;

    public SpringSessionBackedSessionRegistry(FindByIndexNameSessionRepository<S> sessionRepository) {
        Assert.notNull(sessionRepository, "sessionRepository cannot be null");
        this.sessionRepository = sessionRepository;
    }

    @Override
    public List<String> getAllPrincipals() {
        throw new UnsupportedOperationException("SpringSessionBackedSessionRegistry does "
                + "not support retrieving all principals, since Spring Session provides "
                + "no way to obtain that information");
    }

    @Override
    public List<SessionInfo> getAllSessions(String principal, boolean includeExpiredSessions) {
        Collection<S> sessions = this.sessionRepository.findByPrincipalName(principal)
                .values();
        List<SessionInfo> infos = new ArrayList<>();
        for (S session : sessions) {
            if (includeExpiredSessions
                    || !Boolean.TRUE.equals(session.getAttribute(SpringSessionBackedSessionInfo.EXPIRED_ATTR))) {
                infos.add(new SpringSessionBackedSessionInfo<>(session, this.sessionRepository));
            }
        }
        return infos;
    }

    @Override
    public SessionInfo getSessionInfo(String sessionId) {
        S session = this.sessionRepository.findById(sessionId);
        if (session != null) {
            return new SpringSessionBackedSessionInfo<>(session, this.sessionRepository);
        }
        return null;
    }

    @Override
    public void refreshLastRequest(String sessionId) {
    }

    @Override
    public void registerNewSession(String sessionId, String principal) {
    }

    @Override
    public void removeSessionInfo(String sessionId) {
    }

}
